import pymysql
import db_utils
from models import Classroom
class UserManager:
    def __init__(self):
        self.conn = pymysql.connect(host="localhost", user="root", password="123", db="stu", charset="utf8")

    def test(self):
        clas = []
        try:
            cursor = self.conn.cursor()
            sql = "select * from t_classroom where grade=%s"
            cursor.execute(sql, (2015,))
            for s in cursor.fetchall():
                clas.append(Classroom(*s))
        except pymysql.MySQLError as e:
            print(e)
            self.conn.rollback()
        finally:
            cursor.close()
            self.conn.close()
        return clas

    def test1(self):
        clas = []
        conn = db_utils.get_dict_connection()
        try:
            with conn.cursor() as cursor:
                sql = "select * from t_classroom where grade=%s"
                cursor.execute(sql, (2015,))
                for s in cursor.fetchall():
                    clas.append(Classroom(**s))
        except pymysql.MySQLError as e:
            print(e)
            conn.rollback()
        return clas

if __name__ == '__main__':
    um = UserManager()
    clas = um.test1()
    for cla in clas:
        print(cla)
    # clas = um.test()
    # for cla in clas:
    #     print(cla)